package com.adqua.testfacebook;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MyLocation extends FragmentActivity implements LocationListener {

	private GoogleMap mmap;
	private LocationManager locationManager;
	private String provider;
	private LatLng position;
	private double lat;
	private double lng;
	private TextView point_num;
	private BufferedReader br;
	
	AlertDialog exit_alert;
	Button map_btn;
	Button stamp_btn;
	Button barcode_btn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		
		new getMarkerPoint().execute();
		
		point_num = (TextView) findViewById(R.id.lucknum);
		
		map_btn = (Button) findViewById(R.id.map_btn);
		stamp_btn = (Button) findViewById(R.id.stamp_btn);
		barcode_btn = (Button) findViewById(R.id.barcode_btn);
		
		final String fb_name = getIntent().getStringExtra("name");
		final String fb_id = getIntent().getStringExtra("id");
		
		stamp_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MyLocation.this, StampActivity.class);
				intent.putExtra("fb_name", fb_name);
				intent.putExtra("fb_id", fb_id);
				startActivity(intent);
			}
		});
		
		barcode_btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MyLocation.this, BarcodeActivity.class);
				intent.putExtra("fb_name", fb_name);
				intent.putExtra("fb_id", fb_id);
				startActivity(intent);
			}
		});
		
		point_num.setText(getIntent().getStringExtra("name")+getIntent().getStringExtra("id"));

		GooglePlayServicesUtil.isGooglePlayServicesAvailable(MyLocation.this);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_HIGH);
		
		provider = locationManager.getBestProvider(criteria, true);
		Log.i("provider:", provider);

		if (provider == null) { // 위치정보 설정이 안되어 있으면 설정하는 엑티비티로 이동합니다
			new AlertDialog.Builder(MyLocation.this)
					.setTitle("위치서비스 동의")
					.setMessage("위치서비스의 정보를 동의 하셔야 합니다.")
					.setNeutralButton("이동",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
								}
							})
					.setOnCancelListener(new DialogInterface.OnCancelListener() {
								@Override
								public void onCancel(DialogInterface dialog) {
									finish();
								}
							}).show();
		} else { // 위치 정보 설정이 되어 있으면 현재위치를 받아옵니다
			
			if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
				
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("GPS가 비활성화 되어있습니다. 활성화 하시겠습니까?")
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Intent gpsOptionsIntent = new Intent(android.provider.Settings.ACTION_LOCALE_SETTINGS);
						startActivity(gpsOptionsIntent);
					}
				}).setNegativeButton("취소", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
				
			}
			
			locationManager.requestLocationUpdates(provider, 0, 0, MyLocation.this);
			setUpMapIfNeeded(); 
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {// 위치설정 엑티비티 종료 후

		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case 0:
				locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	
				Criteria criteria = new Criteria();
				criteria.setAccuracy(Criteria.ACCURACY_FINE);
				criteria.setAltitudeRequired(false);
				criteria.setBearingRequired(false);
				criteria.setCostAllowed(true);
				criteria.setPowerRequirement(Criteria.POWER_LOW);
				
				provider = locationManager.getBestProvider(criteria, true);
				if (provider == null) {// 사용자가 위치설정동의 안했을때 종료
					finish();
				} else {// 사용자가 위치설정 동의 했을때
					locationManager.requestLocationUpdates(provider, 0, 0, MyLocation.this);
					setUpMapIfNeeded();
				}
			break;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		setUpMapIfNeeded();

	}

	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}
	
	private void setUpMapIfNeeded() {
		if (mmap == null) {
			mmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

			/*
			  mmap.setOnMapClickListener(new OnMapClickListener() { // 맵 클릭시 해당위치로 마커 이동과 함께 animate 하기
			  
			  @Override public void onMapClick(LatLng latLng) { MarkerOptions markerOptions = new MarkerOptions();
			  //markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)); //원하는 아이콘으로 마커 찍기
			  markerOptions.position(latLng); mmap.clear();
			  mmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
			  mmap.addMarker
			  (markerOptions.title("현재위치").snippet("latLng: "+latLng));
			  
			 } });
			 */
			mmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

			if (mmap != null) {
				setUpMap();
			}
		}
	}

	private void setUpMap() {
		mmap.setMyLocationEnabled(true);
		mmap.getMyLocation();

	}

	boolean locationTag = true;

	@Override
	public void onLocationChanged(Location location) {
		if (locationTag) {// 한번만 위치를 가져오기 위해서 tag를 주었습니다

			lat = location.getLatitude();
			lng = location.getLongitude();
			
			String lat_str = Double.toString(lat);
			String lng_str = Double.toString(lng);
	
			position = new LatLng(lat, lng); // 포지션값
			
			Log.i("lat", lat_str);
			Log.i("lng", lng_str);
			
	
			mmap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15)); // 포지션 위치로 이동 시킴과 동시에 15배줌
	
			mmap.addMarker(new MarkerOptions().position(position).title("현재위치").snippet("lat: " + lat + "lng: " + lng)); // 해당 위치에 마커 찍기
	
			mmap.animateCamera(CameraUpdateFactory.newLatLng(position)); // 해당포지션으로 카메라 이동
			
			LocationAlert();
	
			locationTag = false;
			
		 }

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
	}
	
	private void showMsg(String msg){
		Toast.makeText(MyLocation.this, msg, Toast.LENGTH_SHORT).show();
	}
	
	// 파일 생성 후 파일을 읽어오기 위한 시간 지연 핸들러 메소드
	private void LocationAlert() {
        // TODO Auto-generated method stub
       Handler handler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                
            	String c_name = ""; //대리점 및 키오스크 이름
        		String c_lat = ""; // 위도
        		String c_lng = ""; // 경도
        		String c_gubun = ""; // 구분자(a: 대리점, k: 키오스크)
        		
        		try {
        			
        			String sdCardPath = null;
        			sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        			
        			FileInputStream fis = new FileInputStream(sdCardPath + "/point.json");
        			
        			if(fis!=null){
        			
        				br = new BufferedReader(new InputStreamReader(fis));
        				
        				StringBuilder sb = new StringBuilder();
        				
        				int bufferSize = 1024 * 1024;
        				
        				char readBuf [] = new char[bufferSize];
        				int resultSize = 0;
        				
        				while((resultSize = br.read(readBuf)) != -1){
        					if(resultSize == bufferSize){
        						sb.append(readBuf);
        					}else{
        						for (int i = 0; i < resultSize; i++) {
        							sb.append(readBuf[i]);
        						}
        					}
        				}
        				
        				String jString = sb.toString();
        				
        				JSONArray ja = new JSONArray(jString);
        				
        				for (int i = 0; i < ja.length(); i++) {
        					
        					JSONObject jsonObject = ja.getJSONObject(i);
        					
        					c_name = jsonObject.getString("name").toString();
        					c_lat = jsonObject.getString("lat").toString();
        					c_lng = jsonObject.getString("lng").toString();
        					c_gubun = jsonObject.getString("gubun").toString();
        					
        					double lat_d = Double.valueOf(c_lat).doubleValue();
        					double lng_d = Double.valueOf(c_lng).doubleValue();
        					
        					float[] results = new float[3];
        					Location.distanceBetween(lat, lng, lat_d, lng_d, results);
        					float number = results[0];
        					
        					if(c_gubun.equals("a")){
        						if(number<=200){
        							AlertDialog alert = new AlertDialog.Builder(MyLocation.this).setMessage(c_name+"이 200m 안에 있습니다.").setPositiveButton("OK", new DialogInterface.OnClickListener() {
        								@Override
        								public void onClick(DialogInterface dialog, int which) {
        									// TODO Auto-generated method stub
        									dialog.dismiss();
        								}
        							}).show();
        			        	}
        					}
        					
        				}
        			
        			}
        			
        		} catch (JSONException e) {
        			Toast.makeText(MyLocation.this, "JSON을 읽을 수 없습니다.", Toast.LENGTH_SHORT).show();
        			
        		} catch (Exception e){
        			e.printStackTrace();
        			Toast.makeText(MyLocation.this, "파일을 읽을 수 없습니다.", Toast.LENGTH_SHORT).show();
        		}
            	
            }
        };
        handler.sendEmptyMessageDelayed(0, 1500);    // ms, 3초후 종료시킴
    }
	
	
	class getMarkerPoint extends AsyncTask<String, String, String> {
		
		ProgressDialog progDialog = new ProgressDialog(MyLocation.this );

		@Override
		protected void onPostExecute(String result) {
			
			super.onPostExecute(result);
			progDialog.dismiss();
			
			String point_name = null; //대리점 및 키오스크 이름
			String point_lat = null; // 위도
			String point_lng = null; // 경도
			String point_gubun = null; // 구분자(a: 대리점, k: 키오스크)
						
			try {
				
				String ess = Environment.getExternalStorageState();
				String sdCardPath = null;
				
				if(ess.equals(Environment.MEDIA_MOUNTED)){
					sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
					
					try {
						File file = new File(sdCardPath + "/point.json");
						
						FileOutputStream fos;
						fos = new FileOutputStream(file);
						fos.write(result.getBytes());
						fos.close();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						showMsg("지정된 파일을 생성할 수 없습니다.");
					} catch(IOException e){
						showMsg("파일에 데이터를 쓸 수 없습니다.");
					}
					
				}else{
					showMsg("SD Card not ready!");
				}
				
				JSONArray ja = new JSONArray(result);
				
				for (int i = 0; i < ja.length(); i++) {
					
					JSONObject jsonObject = ja.getJSONObject(i);
					
					point_gubun = jsonObject.getString("gubun").toString();
					point_name = jsonObject.getString("name").toString();
					point_lat = jsonObject.getString("lat").toString();
					point_lng = jsonObject.getString("lng").toString();
					
					double lat_d = Double.valueOf(point_lat).doubleValue();
					double lng_d = Double.valueOf(point_lng).doubleValue();
					
					float[] results = new float[3];
					Location.distanceBetween(lat, lng, lat_d, lng_d, results);
					float number = results[0];
					String str_distance = String.format("%.0f", number); //소수점 지우기
					
					//2000m 이내에서만 마커가 찍히도록
					if(number <2000){
				
						if(point_gubun.equals("a")){
							mmap.addMarker(new MarkerOptions().title(point_name).position(new LatLng(lat_d, lng_d)).snippet("거리: " + str_distance + "m").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))); // 대리점
						}
						if(point_gubun.equals("k")){
							mmap.addMarker(new MarkerOptions().title(point_name).position(new LatLng(lat_d, lng_d)).snippet("거리: " + str_distance + "m").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon))); // 키오스크
						}
					}
					
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
			
		    progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		    progDialog.setMessage("대리점 및 키오스크위치를 가져오고 있습니다."); 
		    progDialog.show();

		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected String doInBackground(String... params) {
			
			InputStream is = null;
			String result = null;

			String getUrl = "http://www3.bohae.co.kr/test_xml.php";

			try {
				DefaultHttpClient httpclient = new DefaultHttpClient();
				HttpGet httpget = new HttpGet(getUrl);
				HttpParams paramss = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(paramss, 5000);
				HttpConnectionParams.setSoTimeout(paramss, 5000);
				HttpResponse response = httpclient.execute(httpget);
				HttpEntity entityResponse = response.getEntity();
				is = entityResponse.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "utf-8"), 8);

				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
				is.close();
				result = sb.toString();

			} catch (IOException e) {
				e.toString();
			}
			return result;

		}
	}
}


